import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest } from 'next/server'
import {whiteList} from '@/shared/whiteList'
import { getToken } from "next-auth/jwt"
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
  // referer: 'http://localhost:3000/tagPage/create?kind=expenses',
  // url: 'http://localhost:3000/api/tag',
  // href: 'http://localhost:3000/api/tag',
  // pathname: '/api/tag',
  const nextUrl = req.nextUrl
  const {pathname} = nextUrl
  const headersList = new Headers(req.headers)
  const referer = headersList.get('referer') ?? '/'

  const routeUrl = new URL(referer)
  const routePathName = routeUrl.pathname
  
  const noSessionCheck = Object.keys(whiteList).some(ele=>{
    if(whiteList[ele] === routePathName && whiteList[ele] === 'exact'){
      return true
    }else if(routePathName.startsWith(ele) && whiteList[ele] === 'startsWith' ){
      return true
    }
    return false
  })
  if(noSessionCheck || pathname.indexOf('/api/auth') === 0){
    return NextResponse.next();
  }else{
    const token = await getToken({ req })
    if(!token){
      return NextResponse.json('登录过期',{status: 401})
    }
    return NextResponse.next();
  }
}

export const config = {
  matcher: '/api/:path*',
}